package com.jxt.app.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jxt.app.entity.Apmessages;
import com.jxt.app.entity.Apresource;
import com.jxt.app.entity.ApresourceExample;
import com.jxt.app.service.ApResourceService;
import com.jxt.app.util.Page;


@Controller
public class ResourceController {
	
	
	// 日志记录器
	private static final Logger logger = Logger.getLogger(ResourceController.class);

	@Resource
	private ApResourceService apResourceService;

	
	
	/**
	 * 资源列表不分页查询
	 * @param page
	 * @param type /1听写英语/2优展示/3同步解析/4易错题库
	 * @param pageSize
	 * @param requset
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/app/res/list/{userid}/{isread}/{type}/",method=RequestMethod.GET) 
	public String resListnopage(@PathVariable byte isread,@PathVariable String userid,@PathVariable Byte type,HttpServletRequest requset, Model model) throws UnsupportedEncodingException{
	
		ApresourceExample example=new ApresourceExample();

		example.setType(type);
		example.setType_Indicator(ApresourceExample.EXAMPLE_EQUALS);
		
		
		example.setIsread(isread);
		example.setIsread_Indicator(ApresourceExample.EXAMPLE_EQUALS);
		
	
		HashMap<String,Object> parms=new HashMap<String,Object>();
		parms.put("isread", isread);
		parms.put("userid", userid);
		parms.put("ispush", 0);
		parms.put("type", type);
		
		Page apnewsList = null;
		try {
			apnewsList = apResourceService.findListByJoinMap(parms, 1, 1000000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(null!=apnewsList){
			model.addAttribute("result", apnewsList.getResult());
		}else{
			
			model.addAttribute("result", new ArrayList());
		}
		return "megList";
	}
	
	
	/**
	 * 资源列表
	 * @param page
	 * @param type /1听写英语/2优展示/3同步解析/4易错题库
	 * @param pageSize
	 * @param requset
	 * @param model
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/app/res/list/{userid}/{isread}/{type}/{page}/{pageSize}",method=RequestMethod.GET) 
	public String megList(@PathVariable int page,@PathVariable byte isread,@PathVariable String userid,@PathVariable Byte type,@PathVariable int pageSize,HttpServletRequest requset, Model model) throws UnsupportedEncodingException{
	

		

		HashMap<String,Object> parms=new HashMap<String,Object>();
		parms.put("isread", isread);
		parms.put("userid", userid);
		parms.put("ispush", isread);
		parms.put("type", type);
		
		Page apnewsList = null;
		try {
			apnewsList = apResourceService.findListByJoinMap(parms, page, pageSize);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.addAttribute("result", apnewsList);
		return "megList";
	}
	
	
	
	/**资源上传
	 * 
	 * @param canReply
	 * @param title
	 * @param description
	 * @param dialogId
	 * @param infoType
	 * @param receiveId
	 * @param filetype
	 * @param type /1听写英语/2优展示/3同步解析/4易错题库
	 * @param width
	 * @param p
	 * @param a
	 * @param upImg
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 * @throws FileUploadException
	 */
	 @RequestMapping(value="/app/res/upload",method=RequestMethod.POST) 
	 public void upload_json(Apresource apresource,@RequestParam(required = false, defaultValue = "0")byte canReply,@RequestParam(required = false, defaultValue = "")String filename,String title,@RequestParam(required = false, defaultValue = "0")long sendid,String description,String dialogId,String receiveId,@RequestParam(required = false, defaultValue = "0")byte filetype, @RequestParam(required = false, defaultValue = "1")int type,@RequestParam(required = false, defaultValue = "500")int width,String upImg,HttpServletRequest request,HttpServletResponse response,Model model) throws IOException, FileUploadException {   
		 {
			try{
			 
			
			 logger.debug("----------进入课件上传  -----------");
			 logger.debug("filetype====="+filetype);
			 logger.debug("type"+type);
			 logger.debug("sendid"+sendid);

			 apresource.setType((byte)type);

			 apresource.setFiletype(filetype);
			 apresource.setTitle(title);
			 apresource.setDescription(description);
			 apresource.setCanreply(canReply);
			 apresource.setTime(new Date());
			 apresource.setSysflag((byte)0);
			 apresource.setIschecked((byte)0);
			 apresource.setIspush((byte)0);
			 apresource.setIsread((byte)0);
			 if(null==dialogId||"".equals(dialogId)){
				 dialogId=UUID.randomUUID().toString();
			 }
			 apresource.setDialogid(dialogId);
				
			 logger.debug("----------进入课件上传 2 -----------");
			 response.setContentType("text/html; charset=UTF-8");
			 PrintWriter out = response.getWriter(); 
			 
			//文件保存目录路径
			 String savePath = request.getSession().getServletContext().getRealPath("/") + "attached/";

			 //文件保存目录URL
			 String saveUrl  = request.getContextPath() + "/attached/";

			 //定义允许上传的文件扩展名
			 HashMap<String, String> extMap = new HashMap<String, String>();
			 extMap.put("image", "gif,jpg,jpeg,png,bmp");
			 extMap.put("flash", "swf,flv");
			 extMap.put("course", "mcourse");
			 extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
			 extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

			 //最大文件大小
			 long maxSize = Long.parseLong("10000000000000");

			
			 logger.debug("----------进入课件上传 3333333333 -----------");
			 if(!ServletFileUpload.isMultipartContent(request)){
			 	out.println(getError("请选择文件。"));
			 	return;
			 }
			 //检查目录
			 File uploadDir = new File(savePath);
			 if(!uploadDir.isDirectory()){
			 	out.println(getError("上传目录不存在。"));
			 	return;
			 }
			 //检查目录写权限
			 if(!uploadDir.canWrite()){
			 	out.println(getError("上传目录没有写权限。"));
			 	return;
			 }
			 logger.debug("----------进入课件上传 44444444444 -----------");
			 String dirName = request.getParameter("dir");
			 if (dirName == null) {
			 	dirName = "image";
			 }
			 if(!extMap.containsKey(dirName)){
			 	out.println(getError("目录名不正确。"));
			 	return;
			 }
			 
			 
			 logger.debug("----------进入课件上传 555555555 -----------");
			 //创建文件夹
			 savePath += dirName + "/";
			 saveUrl += dirName + "/";
			 File saveDirFile = new File(savePath);
			 if (!saveDirFile.exists()) {
			 	saveDirFile.mkdirs();
			 }
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			 String ymd = sdf.format(new Date());
			 savePath += ymd + "/";
			 saveUrl += ymd + "/";
			 File dirFile = new File(savePath);
			 if (!dirFile.exists()) {
			 	dirFile.mkdirs();
			 }

			 FileItemFactory factory = new DiskFileItemFactory();
			 ServletFileUpload upload = new ServletFileUpload(factory);
			 upload.setHeaderEncoding("UTF-8");
			 
			 //转型为MultipartHttpRequest(重点的所在)   
	         MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;   
	         //  获得第1张图片（根据前台的name名称得到上传的文件）    
	         List<MultipartFile> imgFileList  =  multipartRequest.getFiles("file");
	           
	         //定义一个数组，用于保存可上传的文件类型   

	         
	         
	         logger.debug("----------imgFileList-----------"+imgFileList.size());
	         //检查文件资源包
			 if(imgFileList.size() ==0){
			 			out.println(getError("没有获取到资源包！"));
			 			return;
			 }
			// List items = upload.parseRequest(request);
	         List items=imgFileList;
			 Iterator itr = items.iterator();
		    for(MultipartFile imgFile:imgFileList){
			 	//FileItem item = (FileItem) itr.next();
			 	String fileName = filename;
			 	long fileSize = imgFile.getSize();
			 		
					//检查文件大小
				 	if(imgFile.getSize() ==0){
				 			out.println(getError("上传文件为0字节。"));
				 			return;
				 	}
			 		//检查文件大小
			 		if(imgFile.getSize() > maxSize){
			 			out.println(getError("上传文件大小超过限制。"));
			 			return;
			 		}
			 		//检查扩展名
			 		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			 		
			 		if(fileExt.equals("mcourse")){	
			 			dirName = "course";
			 		}
			 		if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
			 			out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
			 			return;
			 		}

			 		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			 		String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			 		try{
			 			File uploadedFile = new File(savePath, newFileName);
			 			imgFile.transferTo(uploadedFile); 
			 		}catch(Exception e){
			 			out.println(getError("上传文件失败。"));
			 			return;
			 		}	
			 		
			 		try{
				 		apresource.setUrl(saveUrl + newFileName);
				 		Apresource result=apResourceService.save(apresource,sendid);
				 		
				 		JSONObject obj = new JSONObject();
				 		
				 		obj.put("resid", result.getTime()==null?"":result.getTime().toString());
				 		obj.put("resid", result.getId());
				 		obj.put("code", 1001);
				 		obj.put("time", new Date().getTime());
				 		obj.put("url", saveUrl + newFileName);
				 		out.println(obj.toString());
			 		}catch(Exception e){
			 			e.printStackTrace();
			 			JSONObject obj = new JSONObject();
			 			obj.put("resid", null);
				 		obj.put("code", -1001);
				 		obj.put("time", new Date().getTime());
				 		obj.put("url", saveUrl + newFileName);
				 		out.println(obj.toString());
			 			
			 		}
			 
			 }
			}catch(Exception e){
				 logger.debug("----------进入课件上传异常 -----------");	
				e.printStackTrace();
			}
		 }
		}

		 
		 
			
		
	 private String getError(String message) {
			JSONObject obj = new JSONObject();
			obj.put("code", -1001);
			obj.put("message", message);
			return obj.toString();
		}
}
